//
//  BRSError.m
//  Pint
//
//  Created by xiect on 13-10-29.
//  Copyright (c) 2013年 brains. All rights reserved.
//

#import "BRSError.h"

#import "const.h"
static NSDictionary *errorCodes;

@implementation BRSError

+ (void) initialize {
	NSString *filePath = [[NSBundle mainBundle] pathForResource:kMESSAGE_FILE ofType:@"plist"];
	if(filePath != nil){
		errorCodes = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
	}
    // ERROR NO MESSAGE FILE
}

+ (void) dealloc {
	[super dealloc];
}


-(id) init {
    if ((self = [super init])) {
		return self;
	}
    return self;
}


//===========================================================
//  Keyed Archiving
//
//===========================================================
- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:self.message forKey:@"message"];
    [encoder encodeObject:self.errorCode forKey:@"errorCode"];
}

- (id)initWithCoder:(NSCoder *)decoder{
    if ((self = [super init])) {
        self.message = [decoder decodeObjectForKey:@"message"];
        self.errorCode = [decoder decodeObjectForKey:@"errorCode"];
    }
    return self;
}

- (id)copyWithZone:(NSZone *)zone
{
    id theCopy = [[[self class] allocWithZone:zone] init];  // use designated initializer
	
    [theCopy setMessage:[self.message copy]];
    [theCopy setErrorCode:self.errorCode];
	
    return theCopy;
}
#pragma mark -
#pragma mark super class implementations

-(int) code{
	if([self.errorCode intValue] == 0){
        return [super code];
    }else{
        return [self.errorCode intValue];
    }
}

- (NSString *) domain{
    if([self.errorCode hasPrefix:kPREFIX_MESSAGE] || [self.errorCode hasPrefix:kPREFIX_ERROR]){
        return kBusinessErrorDomain;
    }else{
        return kRequestErrorDomain;
    }
}

- (NSString*) description {
    return [NSString stringWithFormat:@"Request failed with error %@[%@]", self.message, self.errorCode];
}

- (NSString*) localizedDescription {
    if([[self domain] isEqualToString:kBusinessErrorDomain])
        return [[errorCodes objectForKey:self.errorCode] objectForKey:@"Title"];
    else
        return [super localizedDescription];
}

- (NSString*) localizedRecoverySuggestion {
    if([[self domain] isEqualToString:kBusinessErrorDomain])
        return [[errorCodes objectForKey:self.errorCode] objectForKey:@"Suggestion"];
    else
        return [super localizedRecoverySuggestion];
}


- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    NSLog(@"Undefined Key: %@", key);
}

#pragma mark -
#pragma mark Our implementations
-(id) initWithDictionary:(NSMutableDictionary*) jsonObject {
    if((self = [super init])){
        self = [self init];
        [self setValuesForKeysWithDictionary:jsonObject];
    }
    return self;
}

@end
